package com.assessment.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.assessment.entity.Ascore;
import com.assessment.entity.Auser;
import com.assessment.service.AscoreService;
import com.assessment.service.AtypeService;
import com.assessment.service.AuserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.assessment.utils.Constant.*;
import static com.assessment.utils.ReturnMap.failedMap;
import static com.assessment.utils.ReturnMap.successMap;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鑫十一
 * @since 2021-12-15
 */
@CrossOrigin("*")
@RestController
@Api(tags={"更改密码"})
@RequestMapping("/api")
public class PwdApi {
    private static final Logger log = LoggerFactory.getLogger(PwdApi.class);
    @Autowired(required = false)
    private AuserService auserService;
    // 更新
    @PostMapping("/changePwd")
    public Map<String, Object> changePwd(@RequestBody String item) {
        try {
            JSONObject jsonObject = JSON.parseObject(item);
            String account = jsonObject.getString("account");
            String pwd = jsonObject.getString("pwd");
            String newPwd = jsonObject.getString("newPwd");
            String confirmPwd = jsonObject.getString("confirmPwd");
            if (!newPwd.equals(confirmPwd)){
                return failedMap("两次密码不一致！");
            }

            QueryWrapper<Auser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", account);
            List<Auser> list = auserService.list(queryWrapper);
            Auser auser = list.get(0);
            if (!auser.getPwd().equals(pwd)){
                return failedMap("旧密码错误！");
            }
            log.info("更改之前：{}", auser);
            auser.setPwd(newPwd);
            log.info("更改之后：{}", auser);
            return auserService.updateById(auser)? successMap(UPDATE_SUCCESS):failedMap(UPDATE_FAILED);

        }catch (Exception e){
            e.printStackTrace();
            return failedMap(UPDATE_FAILED);
        }
    }

}

